package com.zonda.sampleretrofit2.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class RatioImageView extends ImageView{

  private static final float MAX_ASPECT_RATIO_DEFORMATION_FRACTION = 0.01f;

  private static final float DEFAULT_RATIO = 16 / 9.0f;

  private float mWidthHeightRatio = DEFAULT_RATIO;

  public RatioImageView(Context context) {
    super(context);
  }

  public RatioImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int measuredWidth = getMeasuredWidth();

    int measuredHeight = getMeasuredHeight();

    if (measuredWidth != 0) {

      Log.i(getClass().getSimpleName(), " measuredWidth is " + measuredWidth);

      if (measuredHeight != 0) {
        final float viewAspectRatio = measuredWidth / (measuredHeight * 1.0f);

        float aspectDeformation = mWidthHeightRatio / viewAspectRatio - 1;

        if (Math.abs(aspectDeformation) <= MAX_ASPECT_RATIO_DEFORMATION_FRACTION) {
          // We're within the allowed tolerance.
          return;
        }
      }

      measuredHeight = (int) (measuredWidth / mWidthHeightRatio);

      setMeasuredDimension(measuredWidth, measuredHeight);
    } else {
      Log.i(getClass().getSimpleName(), " measuredWidth is zero , may be error ~");
    }
  }

  public void setWidthHeightRatio(float widthHeightRatio) {
    if (widthHeightRatio > 0) {
      this.mWidthHeightRatio = widthHeightRatio;
    }
  }
}
